#include "TimerManager.h"

#ifdef __COMPILE_LINUX__
	#include <stdio.h>
	#include <time.h>
	#include <sys/time.h>
#endif

#ifdef __COMPILE_WIN32__
	#define DESIRED_TIME_RESOLUTION		1
	#include <windows.h>
	#ifdef _MSC_VER
		#pragma comment(lib, "Winmm.lib")
	#endif
#endif

#include "include/ILog.h"

CTimerManager::CTimerManager()
{
	tlist.clear();
#ifdef __COMPILE_WIN32__
	timeBeginPeriod(DESIRED_TIME_RESOLUTION);
#endif
	ActualTime = GetRealClockTime();
	pLogRelease << "TimerManager created..." << endl;
}

CTimerManager::~CTimerManager()
{
#ifdef __COMPILE_WIN32__
	timeEndPeriod(DESIRED_TIME_RESOLUTION);
#endif

	tlist.DeleteListNodes();
}

u32 CTimerManager::GetRealClockTime()
{
#ifdef __COMPILE_WIN32__
	return timeGetTime();
#endif

#ifdef __COMPILE_LINUX__
	timeval tv;
	gettimeofday(&tv, 0);
	return (u32)(tv.tv_sec * 1000) + (tv.tv_usec / 1000);
#endif
}

u32 CTimerManager::GetActualTime()
{
	return ActualTime;
}

u32 CTimerManager::GetFrameTime()
{
	return FrameTime;
}

ITimer *CTimerManager::GetNewTimer()
{
	ITimer *Temp = new ITimer();
	tlist.push_back(Temp);

	return Temp;
}

bool CTimerManager::StartTimer(ITimer *t)
{
	t->Start(GetActualTime());
	return true;
}

void CTimerManager::SetAndStartTimer(ITimer *t,u32 Time)
{
	t->SetTime(Time);
	StartTimer(t);
}

u32 CTimerManager::Update()
{
	u32 ne = 0;
	u32 at = GetRealClockTime();
	FrameTime = at - ActualTime;
	ActualTime = at;

	for (TimerList::iterator it=tlist.begin();it!=tlist.end();it++)
	{
		(*it)->Update(ActualTime);
		ne++;
	}

	return ne;
}

bool CTimerManager::DeleteTimer(ITimer *t)
{
	return tlist.DeleteNode(t);
}
